;
(function (window, angular) {
    'use strict';
    angular.module("Controller.BasicData.Supple", [])
        .controller("SuppleCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.materialObj = {
                mainMaterialList: [],
                accessoriesList: []
            };

            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMaterielOriginal: false,
                showMaterielDismantling: false
            };
            $scope.dataList = [];
            $scope.detailObj = "";
            $scope.tbConf = {
                fixedWidth: 200,
                scrollWidth: 1220,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "辅料零件号",
                        dataField: "excipientNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "辅料零件中文名",
                        dataField: "excipientDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "绑定数量",
                        dataField: "bindingQty",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createTimeStr",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createrName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "修改时间",
                        dataField: "updateTimeStr",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "修改人",
                        dataField: "updateName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            //新增零件主料列表配置项
            $scope.mainMaterialTbConf = {
                fixedWidth: 340,
                scrollWidth: 800,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },

                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            //新增零件辅料列表配置项
            $scope.accessoriesListTbConf = {
                fixedWidth: 340,
                scrollWidth: 800,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "数量",
                        dataField: "bindingQty",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        input: true,
                        inputType: "txt"
                    }
                ]
            };

            $scope.inTypeList = [];

            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/excipient/exportAllConfig")
            };

            var btnPermissionCode = {};

            $scope.btnPermission = {};

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    fixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.materialObj = {
                    headerInfo: {},
                    mainMaterialList: [],
                    accessoriesList: []
                };
                $scope.materialObj.headerInfo.splitType = 0;
                $scope.tabFlag = {};
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMaterielOriginal = false;
                $scope.toolbarConfig.showMaterielDismantling = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                var service = "device";
                var reqUrl = "/excipient/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    translateField();
                });
            }


            $scope.delSign = function (code) {
                var codeList = [code];
                delFunc(codeList);
            };

            $scope.delBatch = function () {
                var codeList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        codeList.push(item.id);
                    }
                });
                delFunc(codeList);
            };

            function delFunc(CodeList) {
                if (CodeList.length == 0) {
                    ybWidget.ShowMessage('请选择要删除的数据');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    ybHttp.Post(service, '/excipient/delete', CodeList).then(function (data) {
                        if (data.code !== 0) {
                            ybWidget.ShowMessage(data.message);
                            return;
                        }
                        getDataList();
                    })
                })
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };


            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };


            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };

            var getDataDetail = function (materialsNo) {
                var service = "device";
                var reqUrl = "/excipient/listByMaterialsNo";
                return ybHttp.Get(service, reqUrl, {materialsNo: materialsNo}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            };

            //编辑按钮
            $scope.editData = function (item) {
                getDataDetail(item.materialsNo).then(function (resp) {
                    $scope.materialObj = angular.copy(resp.value);
                    $scope.materialObj.mainMaterialList = [];
                    $scope.materialObj.accessoriesList = [];
                    $scope.materialObj.mainMaterialList = splitMaterialFn("mainMaterial", resp.value);
                    $scope.materialObj.accessoriesList = splitMaterialFn("accessories", resp.value);
                    $scope.changeTab(2);
                })
            };

            //新增按钮
            $scope.addData = function () {
                $scope.changeTab(1);
            };

            //选择零件按钮
            $scope.selMateriel = function (e, showMaterielType) {
                if (!!$scope.toolbarConfig[showMaterielType]) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig[showMaterielType] = true;
                        $timeout(() => {
                            EventBus.Publish("getMaterial");
                        })
                    });
                }
            };


            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.delChoosedMaterial = function (index) {
                $scope.materialObj.accessoriesList.splice(index, 1);
            };


            $scope.saveData = function (saveType) {
                if ($scope.materialObj.mainMaterialList.length < 1 || $scope.materialObj.accessoriesList.length < 1) {
                    ybWidget.ShowToaster('error', '请至少选择1个主料和辅料');
                    return
                }
                if ($scope.materialObj.accessoriesList.length > 2) {
                    ybWidget.ShowToaster('error', '最多只能选择2个辅料');
                    return
                }

                if ($scope.materialObj.accessoriesList.length > 2) {
                    ybWidget.ShowToaster('error', '最多只能选择2个辅料');
                    return
                }

                var service = "device";
                var param = {};
                var reqUrl = "/excipient/insert";
                if (saveType === "edit") {
                    reqUrl = "/excipient/update";
                }

                param.materialsNo = $scope.materialObj.mainMaterialList[0].materialsNo;
                param.excipients = [];

                angular.forEach($scope.materialObj.accessoriesList, function (item) {
                    var objTemp = {bindingQty: item.bindingQty, excipientNo: item.materialsNo};
                    param.excipients.push(objTemp);
                });

                for (var i = 0; i < param.excipients.length; i++) {
                    if (!param.excipients[i].bindingQty) {
                        ybWidget.ShowToaster('error', '请填写辅料数量');
                        return;
                    }
                }

                saveData(service, reqUrl, param).then(function (value) {
                    if (value) {
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList(1);
                        $scope.changeTab(0);
                    }
                })
            };

            //获取详情时区分materialList的主料与辅料
            function splitMaterialFn(matType, objList) {
                var tempArray = [];
                if (matType === "mainMaterial") {
                    var obj = {};
                    obj.materialsNo = objList[0].materialsNo;
                    obj.materialsDes = objList[0].materialsDes;
                    obj.unit = objList[0].unit;
                    tempArray.push(obj);
                    return tempArray
                }

                angular.forEach(objList, function (item) {
                    var obj = {};
                    obj.materialsNo = item.excipientNo;
                    obj.materialsDes = item.excipientDesc;
                    obj.unit = item.excipientUnit;
                    obj.bindingQty = item.bindingQty;
                    tempArray.push(obj);
                });
                return tempArray;
            }

            function saveData(service, reqUrl, param) {
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            }


            //翻译字段
            function translateField() {
                angular.forEach($scope.dataList, function (item) {
                    item.updateTimeStr = $filter('YbDate')(item.updateTime, "yyyy-MM-dd HH:mm:ss");
                    item.createTimeStr = $filter('YbDate')(item.createTime, "yyyy-MM-dd HH:mm:ss");
                });
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);